import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/404"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const token = store.state.login.token;
  const name = store.state.login.userInfo.name;
  if (token) {
    if (to.path === "/login") {
      next("/dashboard");
    }

    if (name) {
      next();
    } else {
      try {
        await store.dispatch("login/getUserInfo");
        return next();
      } catch (error) {
        store.commit("login/CLEAR_TOKENANDUSERINFO");
        return next("/login");
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      return next();
    } else {
      return next("/login");
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
